<template>
  <el-row class="common-pd-page arrange-inp-box">
    <HPModuleTitle v-if="titleVisiable" :titleText="'面试反馈时间'" />
    <el-form
      :label-position="'right'"
      ref="formData"
      :rules="checkForm"
      label-width="120px"
      :model="formData"
      :class="'form-box'"
    >
      <el-col :span="20" :class="'arrange-form-item'">
        <el-form-item label="面试时间：" prop="inverviewTime">
          <el-date-picker
            v-model="formData.inverviewDate"
            :picker-options="pickerOptions"
            type="date"
            :value-format="'yyyy-MM-dd HH:mm'"
            @change="dateChange"
            placeholder="选择日期"
            style="width: 180px"
          >
          </el-date-picker>
          <el-tooltip class="item" effect="dark" content="为合理安排面试时间，请确认具体时间段" placement="top-start">
            <el-time-picker
              v-model="formData.inverviewTime"
              :disabled="!formData.inverviewDate"
              :picker-options="timeOption"
              value-format="HH:mm"
              format="HH:mm"
              placeholder="选择时间"
              ref="timePicker"
              style="width: 180px"
            >
            </el-time-picker>
          </el-tooltip>
          
        </el-form-item>
      </el-col>
      <el-col :span="20" :class="'arrange-form-item'">
        <el-form-item label="备注：">
          <el-input v-model="formData.desc" :maxlength="500"></el-input>
          <span class="tips">{{ interviewType === '线上面试'? '若面试形式为线上面试，请建立对应时间段的线上腾讯会议链接，并填入备注处': '' }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="20" :class="'arrange-form-item'">
        <el-form-item>
          <el-button
            :class="'save-md-btn'"
            :disabled="isCan"
            @click="sendFeedBackInfo('formData')"
            >发送</el-button
          >
          <span class="send-ex"
            >（提示：如果面试时间不在所给的时间范围内，请提前联系面试官确定。） </span
          >
        </el-form-item>
      </el-col>
    </el-form>
  </el-row>
</template>
<script>
import moment from "moment";
import HPModuleTitle from "@/components/HPModuleTitle.vue";

function fetchInvterviewInpInfo(store, opts) {
  return store.dispatch("FETCH_INTER_VIEW_INPINFO", opts);
}
export default {
  //props: ['interviewId', 'needsCvId'],
  components: {
    HPModuleTitle,
  },
  props: {
    interviewId: {
      type: String,
      default: "",
    },
    needsCvId: {
      type: [String, Number],
      default: "",
    },
    isCloseNeeds: {
      type: Boolean,
      default: false,
    },
    interviewTime: {
      type: String,
      default: "",
    },
    titleVisiable: {
      type: Boolean,
      default: true
    },
    onSubmit: {
      type: Function,
      default: null
    },
    interviewType: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      formData: {
        inverviewTime: "",
        desc: "",
        interviewId: "",
        tempTime: "",
        needsCvId: "",
        inverviewDate: "",
      },
      isCan: false,
      pickerOptions: {
        disabledDate: (time) => {
          if(!this.interviewTime) return false
          console.log(this.interviewTime)
          const [time1] = this.interviewTime.split(",");
          // , time2, time3
          // console.log(this.getStartDate(time1), this.getStartTime(time1), this.getEndDate(time1), this.getEndTime(time1))
          const startTime1 =
            time1 && moment(this.getStartDate(time1) + " 00:00:00").format("x");
          const endTime1 =
            time1 &&
            moment(
              this.getEndDate(time1) +
                (this.getEndTime(time1) === "00:00" ? " 00:00:00" : " 23:59:59")
            ).format("x");
          // const startTime2 =
          //   time2 && moment(this.getStartDate(time2) + " 00:00:00").format("x");
          // const endTime2 =
          //   time2 &&
          //   moment(
          //     this.getEndDate(time2) +
          //       (this.getEndTime(time2) === "00:00" ? " 00:00:00" : " 23:59:59")
          //   ).format("x");
          // const startTime3 =
          //   time3 && moment(this.getStartDate(time3) + " 00:00:00").format("x");
          // const endTime3 =
          //   time3 &&
          //   moment(
          //     this.getEndDate(time3) +
          //       (this.getEndTime(time3) === "00:00" ? " 00:00:00" : " 23:59:59")
          //   ).format("x");

          const disabled1 =
            time.getTime() < startTime1 || time.getTime() >= endTime1;
          // const disabled2 =
          //   time.getTime() < startTime2 || time.getTime() > endTime2;
          // const disabled3 =
          //   time.getTime() < startTime3 || time.getTime() > endTime3;

          let reg = disabled1;
          // if (time2) {
          //   reg = disabled1 && disabled2;
          // }
          // if (time3) {
          //   reg = disabled1 && disabled2 && disabled3;
          // }

          const nowTime = moment().format("x");
          
          if (
            (!time1 || nowTime > moment(time1.split(" - ")[1]).format("x")) 
            // &&(!time2 || nowTime > moment(time2.split(" - ")[1]).format("x")) &&
            // (!time3 || nowTime > moment(time3.split(" - ")[1]).format("x"))
          ) {
            const date = moment().format("yyyy-MM-DD");
            reg = time.getTime() < moment(`${date} 00:00:00`).format("x");
          }

          return (
            reg ||
            time.getTime() <
              moment(moment().format("yyyy-MM-DD") + " 00:00:00").format("x")
          );
        },
      },
      timeOption: {},
      defaultTime: "",
      checkForm: {
        inverviewTime: [
          {
            required: true,
            type: "string",
            message: "请选择面试时间",
            trigger: "submit",
          },
        ],
      },
    };
  },
  beforeMount() {
    let id = this.$route.params.id;
  },
  mounted() {},
  methods: {
    getStartDate(time) {
      const startDay = time.split(" - ")[0].split(" ")[0];
      return startDay;
    },
    getEndDate(time) {
      return time.split(" - ")[1].split(" ")[0];
    },
    getStartTime(time) {
      return time.split(" - ")[0].split(" ")[1];
    },
    getEndTime(time) {
      return time.split(" - ")[1].split(" ")[1];
    },
    dateChange(val) {
      const [time1, time2, time3] = this.interviewTime.split(",");
      if (!val) return;
      const list = this.interviewTime.split(",");
      const checkDate = val.split(" ")[0]; // 选中的日期
      const nowDate = moment().format("yyyy-MM-DD"); // 今天

      let start = "";
      let end = "";

      const timeArr = [];

      list.forEach((item) => {
        if (!item) return;
        const startDateTime = item.split(" - ")[0]; // 开始日期(天/时间)
        const startDay = startDateTime.split(" ")[0]; // 开始日期(天)
        const endDateTime = item.split(" - ")[1]; // 结束日期(天/时间)
        const endDay = endDateTime.split(" ")[0]; // 结束日期(天/时间)
        if (startDateTime.includes(checkDate)) {
          start = startDateTime.split(" ")[1];
          end = endDateTime.includes(checkDate)
            ? endDateTime.split(" ")[1]
            : "23:59";
        } else if (endDateTime.includes(checkDate)) {
          start = "00:00";
          end = endDateTime.split(" ")[1];
        } else {
          start = "00:00";
          end = "23:59";
        }

        // 如果选择的这一天在三个面试时间之间，push时间选择范围

        if (
          moment(checkDate).isBetween(moment(startDay), moment(endDay)) ||
          ((checkDate === startDay || checkDate === endDay) &&
            moment().isBefore(moment(endDateTime)))
        ) {
          const now = moment().format("HH:mm");
          const isTimeAfter = moment(now, "HH:mm").isAfter(
            moment(start, "HH:mm")
          );
          console.log(moment(now, "HH:mm"), moment(start, "HH:mm") )
          console.log(
            checkDate,
            nowDate,
            start,
            moment(now, "HH:mm").isAfter(moment(start, "HH:mm"))
          );
          console.log('时间范围之内')
          console.log(checkDate === nowDate)
          timeArr.push(`${ (!isTimeAfter || checkDate === nowDate) ? now : start}:00 - ${end}:00`);
        }
      });

      // 这里用$set, 直接赋值数组不一定能监听到
      this.$set(
        this.timeOption,
        "selectableRange",
        timeArr.length ? timeArr : [`00:00:00 - 23:59:59`]
      );
      this.formData.inverviewTime = "";

      // 判断选择是不是当天，并且当天不在三个时间范围之内，只允许选当前时间之后的时间
      const nowTime = moment().format("x");
      if (
        (!time1 || nowTime > moment(time1.split(" - ")[1]).format("x")) &&
        (!time2 || nowTime > moment(time2.split(" - ")[1]).format("x")) &&
        (!time3 || nowTime > moment(time3.split(" - ")[1]).format("x"))
      ) {
        if (checkDate === nowDate) {
          start = moment().format("HH:mm");
          this.timeOption.selectableRange = [`${start}:00 - 23:59:59`];
        }
      }

    },
    sendFeedBackInfo(val, ev) {
      let self = this;
      // if (this.isCloseNeeds) {
      //   this._showMessage("error", "此需求已关闭！");
      //   return;
      // }
      this.formData.interviewId = this.interviewId;
      this.formData.needsCvId = this.needsCvId;
      this.formData.tempTime = `${ this.formData.inverviewDate.split(" ")[0] } ${this.formData.inverviewTime}:00`;
      // console.log(this.formData)
      this.$refs[val].validate((valid) => {
        if (valid) {
          if(this.onSubmit) {
            this.onSubmit(this.formData)
            return
          }

          this.$confirm("是否提交面试安排信息?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            customClass: "d-message-box",
            confirmButtonClass: "mes-confir-btn",
            cancelButtonClass: "mes-cancel-btn",
          })
            .then(() => {
              this.isCan = true;
              
              // console.log(this.formData)
              // return
              fetchInvterviewInpInfo(this.$store, this.formData).then(() => {
                let tempObj = this.$store.getters.saveFeedBackInfo;
                if (tempObj.state === "0000") {
                  const { formQuery } = self.$route.query
                  this._showMessage("success", tempObj.message, function () {
                    self.$router.push({
                      path: "/arrange",
                      query: {
                        formQuery
                      }
                    });
                  });
                } else {
                  this._showMessage("error", tempObj.message);
                }
              });
            })
            .catch(() => {});
        } else {
          this.isCan = false;
          return false;
        }
      });
    },
    _showMessage(type, msg, fn) {
      this.$message({
        showClose: false,
        message: msg,
        type: type,
        duration: 1500,
        onClose: function () {
          if (fn instanceof Function) {
            fn && fn();
          }
        },
      });
    },
  },
};
</script>
<style lang="scss">
@import "./../../assets/scss/mixins.scss";
@include resMessageBox;
.arrange-inp-box {
  // background-color: #fff;
  margin-bottom: 20px;
  // border-radius: 6px;
  p {
    text-align: left;
    padding: 20px 20px 30px;
  }
  .form-box {
    border-bottom: none;
    margin-top: 20px;
    margin-bottom: 20px;
    .el-form-item__content {
      width: 80%;
      text-align: left;
    }
    .el-date-editor.el-input,
    .form-box .el-date-editor.el-input__inner {
      width: 100%;
    }
    .arrange-form-item {
      float: none;
      margin: 0px auto;
    }
  }
  .send-ex {
    font-size: 12px;
    color: #999999;
  }
  .tips {
    color: #00A1D6;
    font-size: 12px;
  }
}
</style>
